package com.cdvtc.news.web.admin;

import com.cdvtc.news.entity.Admin;
import com.cdvtc.news.entity.Category;
import com.cdvtc.news.entity.News;
import com.cdvtc.news.entity.Tag;
import com.cdvtc.news.service.CategoryService;
import com.cdvtc.news.service.NewsService;
import com.cdvtc.news.service.Page;
import com.cdvtc.news.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TagService tagService;

    @Autowired
    private ServletContext servletContext;

    @RequestMapping
    public String list(Integer page, Integer size, Model model) {
        Page<News> pagedNews = newsService.getPagedNews(page, size);
        model.addAttribute("pagedNews", pagedNews);
        return "admin/news-list";
    }

    @RequestMapping("add")
    public String add(Model model) {
        List<Category> categories = categoryService.getAllCategories();
        List<Tag> tags = tagService.getAllTags();
        model.addAttribute("categories", categories);
        model.addAttribute("tags", tags);

        return "admin/news-edit";
    }
    @RequestMapping("edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        News news = newsService.getNewsById(id);
        model.addAttribute("news", news);

        List<Category> categories = categoryService.getAllCategories();
        List<Tag> tags = tagService.getAllTags();
        model.addAttribute("categories", categories);
        model.addAttribute("tags", tags);

        return "admin/news-edit";
    }

    @RequestMapping("save")
    public String save(@ModelAttribute News news, @RequestParam HashSet<Integer> tagIds, HttpSession session) throws IOException {
        if (news.getImgFile() != null && !news.getImgFile().isEmpty()) { //上传文件不为空时才处理上传图片
            String path = servletContext.getRealPath("/img");  //获取图片存储路径（服务器端目录）
            String fileName = news.getImgFile().getOriginalFilename();

            //为避免文件名重复，使用UUID文件名
            UUID uuid = UUID.randomUUID();
            File file = new File(path, uuid.toString() + fileName.substring(fileName.indexOf(".")));

            news.getImgFile().transferTo(file);  //写入文件
            news.setImg(file.getName());  // 保存文件名
        }

        Admin admin = (Admin) session.getAttribute("admin");
        news.setEditor(admin);

        if (news.getId() != null) { //更新
            newsService.updateNews(news);
            tagService.updateTagsForNews(news.getId(), tagIds);
        } else { //新增
            if (news.getImg() == null) {
                news.setImg("news.jpg"); //使用默认图片
            }
            news.setPubDate(new Date());
            int newsId = newsService.addNews(news);
            tagService.addTagsForNews(newsId, tagIds);
        }

        return "redirect:/admin/news";
    }
}
